package com.nulldev.util.internal.backport.httpclient_rw.httpclient;

import java.io.IOException;
import java.io.InputStream;

import com.nulldev.util.VariableAPI.RandomUtil;
import com.nulldev.util.data.Variables;
import com.nulldev.util.io.IOUtils;

class BackportInputStreamMonitored extends InputStream {

	private final int UUID = RandomUtil.randomInt();

	private final InputStream _passthrough;
	private long last_read_from = -1;

	public BackportInputStreamMonitored(final InputStream passthrough) {
		this._passthrough = Variables.requireNonNullObject(passthrough, "passthrough");
		BackportInputStreamMonitor.get().register(this);
	}

	@Override
	public int read() throws IOException {
		this.last_read_from = System.currentTimeMillis();
		return _passthrough.read();
	}

	@Override
	public int read(final byte[] b) throws IOException {
		this.last_read_from = System.currentTimeMillis();
		return _passthrough.read(b);
	}

	@Override
	public int read(final byte[] b, final int off, final int len) throws IOException {
		this.last_read_from = System.currentTimeMillis();
		return _passthrough.read(b, off, len);
	}

	@Override
	public int available() throws IOException {
		return _passthrough.available();
	}

	@Override
	public synchronized void mark(final int readlimit) {
		_passthrough.mark(readlimit);
	}

	@Override
	public boolean markSupported() {
		return _passthrough.markSupported();
	}

	@Override
	public synchronized void reset() throws IOException {
		_passthrough.reset();
	}

	@Override
	public long skip(final long n) throws IOException {
		return _passthrough.skip(n);
	}

	@Override
	public void close() throws IOException {
		BackportInputStreamMonitor.get().unregister(this);
		_passthrough.close();
	}

	long get_last_read_to() {
		return this.last_read_from;
	}

	void killConnection() {
		IOUtils.closeQuietly(this);
	}

	@Override
	public int hashCode() {
		return this.UUID;
	}
}
